package cn.exrick.xboot.core.common.aop

import cn.exrick.xboot.core.common.exception.XbootException
import org.aspectj.lang.ProceedingJoinPoint
import org.aspectj.lang.annotation.Around
import org.aspectj.lang.annotation.Pointcut
import org.springframework.validation.Errors
import org.springframework.validation.FieldError
import org.springframework.validation.ObjectError


open class ParamValidateAspect {

    /**
     * Controller层切点,注解方式
     */
    @Pointcut("@annotation(cn.exrick.xboot.core.common.annotation.ParamValid)")
    open fun controllerAspect() {

    }

    /**
     * 配置前置通知,使用在方法aspect()上注册的切入点,同时接受JoinPoint切入点对象,可以没有该参数
     * @param pjp
     * @return
     * @throws Throwable
     */
    @Around("aspect()")
    @Throws(Throwable::class)
    open fun around(pjp: ProceedingJoinPoint): Any? {
        before(pjp)
        return pjp.proceed()
    }

    /**
     *
     * @param pjp
     */
    open fun before(pjp: ProceedingJoinPoint) {

        val params = pjp.args
        var errors: Errors? = null
        for (param in params) {
            if (param is Errors) {
                errors = param
            }
        }
        //验证参数合法性
        validateParams(errors)
    }


    /**
     * 参数验证
     */
     open fun validateParams(errors: Errors?) {

        if (errors != null && errors.hasErrors()) {

            val errorList: List<ObjectError> = errors.allErrors
            val sb = StringBuilder()
            val fieldError = errorList[0] as FieldError
            sb.append(fieldError.defaultMessage)
            throw XbootException(sb.toString().trim { it <= ' ' })
        }
    }
}